'use strict';

const BaseController = require('../../core/base_controller');

class JobOpeningController extends BaseController {

    async userJobView(){
        const { ctx } = this;
        const { id } = ctx.params;
        const {user_id} = ctx.request.headers
        let data = await ctx.model.JobOpening.findByPk(id)
        if(!data){
            ctx.throw(500,'该职位不存在')
        }
        // 当企业发布的职位用户浏览的情况下
        if(data.user_id!==user_id){
            await data.update({views_count:(data.views_count || 0)+1})
            let isBrowse = await ctx.model.UserBrowse.findOne({
                where:{browse_id:id,user_id,type:'job'}
            })
            if(!isBrowse){
                await ctx.model.UserBrowse.create({
                    browse_id:id,
                    type:'job',
                    user_id
                })
            }
        }
        this.success()
    }
    async userJobCollect(){
        const { ctx } = this;
        const { id } = ctx.params;
        const {user_id} = ctx.request.headers
        let data = await ctx.model.JobOpening.findByPk(id)
        if(!data){
            ctx.throw(500,'该职位不存在')
        }
        if(data.user_id!==user_id){
            let isCollect = await ctx.model.UserCollect.findOne({
                where:{collect_id:id,user_id,type:'job'}
            })
            if(!isCollect){
                await ctx.model.UserCollect.create({
                    collect_id:id,
                    type:'job',
                    user_id
                })
            }else{
               await isCollect.destroy()
            }
        }

        this.success()
    }
    async userJobList(){
        const { ctx } = this;
        const {type,pageSize=10,page=1,position_id='',sort='',cuisine='',maxSalary='',minSalary='',experience=''} = ctx.query
        const where = {
            del_flag: 0,
            user_type:'employer',
            status:1
        };

        let order = []
        if(cuisine) where['cuisine_ids'] = {
            [ctx.model.Sequelize.Op.regexp]: `(^|,)${cuisine}(,|$)`
        }
        if(experience) where['work_experience_id'] =  experience
        if(minSalary) where['min_salary'] = {[ctx.model.Sequelize.Op.gte]:minSalary}
        if(maxSalary) where['max_salary'] = {[ctx.model.Sequelize.Op.lte]:maxSalary}
        if(position_id) where['position_id'] = position_id;
        if(sort){
            if(sort==='public_time__desc') order.push(['public_time','DESC'])
            if(sort==='salary__desc') order.push(['max_salary','DESC'])
            if(sort==='salary__asc') order.push(['max_salary','ASC'])
        }  else {
            order.push(['public_time','DESC'])
        }
        // type 参数 ：latest/urgent/nearby
        if(type==='latest'){
            order.push(['public_time','DESC'])
        }else if(type==='urgent'){
            where.is_urgent=1;
        }else if(type==='nearby'){
            where.is_urgent=1;
        }
        const { count, rows } = await ctx.model.JobOpening.findAndCountAll({
            where,
            order,
            offset: (page - 1) * pageSize,
            attributes:[
                'id',
                'position_id',
                'user_id',
                'public_time',
                'work_place',
                'work_experience_id',
                'cuisine_ids',
                'min_salary',
                'user_type',
                'max_salary'
            ],
            limit: parseInt(pageSize),
            include: [
                { model: ctx.model.Position, as: 'position',attributes: ['name', 'id'] },
                { model: ctx.model.DictionaryDetail, as: 'workExperience',attributes: ['dict_value', 'dict_key','id'] },
            ]
        });
        for (let itemJob of rows) {
            itemJob = itemJob.dataValues;
            let cuisine_ids = itemJob.cuisine_ids ? itemJob.cuisine_ids.split(',') : [];
            const employer = await ctx.model.EmployerInfo.findOne({
                where: {
                    user_id:itemJob.user_id
                },
                attributes:['legal_representative','name','phone_number','avatar']
            });
            const cuisines = await ctx.model.DictionaryDetail.findAll({
                where: {
                    dict_key: {
                        [ctx.model.Sequelize.Op.in]: cuisine_ids
                    }
                } ,
                attributes:['dict_value','dict_key','id']
            });
            itemJob.employer = employer
            itemJob.cuisines = cuisines
        }
        this.success({
            list: rows,
            pagination: {
                total: count,
                current: parseInt(page),
                pageSize: parseInt(pageSize),
            }
        })
    }
    async employerJobList(){
        const { ctx } = this;
        const {user_id} = ctx.request.headers
        const { status='', page = 1, pageSize = 10 } = ctx.query;

        const where = {
            del_flag: 0,
            user_id
        };
        if(status) where.status = status;
        const { count, rows } = await ctx.model.JobOpening.findAndCountAll({
            where,
            order: [['created_at', 'DESC']],
            offset: (page - 1) * pageSize,
            limit: parseInt(pageSize),
            attributes:['id','public_time','min_salary','max_salary','work_place','work_experience_id','position_id','status'],
            include: [
                { model: ctx.model.Position, as: 'position',attributes: ['name', 'id'] },
                { model: ctx.model.DictionaryDetail, as: 'workExperience',attributes: ['dict_value', 'dict_key','id'] },
            ]
        });

        this.success({
            list: rows,
            pagination: {
                total: count,
                current: parseInt(page),
                pageSize: parseInt(pageSize),
            }
        })
    }
    async employerDetail() {
        const { ctx } = this;
        const { id } = ctx.params;
        const {user_id} = ctx.request.headers
        const {limit=5} = ctx.query
        let job = await ctx.model.JobOpening.findByPk(id, {
            include: [
                { model: ctx.model.Position, as: 'position',attributes: ['name', 'id'] },
                { model: ctx.model.DictionaryDetail, as: 'workExperience',attributes: ['dict_value', 'dict_key','id'] },
            ]
        });
        if (!job) {
            ctx.throw(500, '职位不存在');
        }
        job = job.dataValues
        let cuisine_ids = job.cuisine_ids? job.cuisine_ids.split(',') : [];
        const cuisines = await ctx.model.DictionaryDetail.findAll({
            where: {
                dict_key: {
                    [ctx.model.Sequelize.Op.in]: cuisine_ids
                }
            },
            attributes:['dict_value','dict_key','id']
        });
        if(job.user_id!==user_id){
            const collect = await ctx.model.UserCollect.findOne({
                where:{collect_id:id,user_id}
                }
            )
            job.is_collect = !!collect
        }

        const employer = await ctx.model.EmployerInfo.findOne({
            where: {
                user_id:job.user_id
            },
            attributes:['legal_representative','name','phone_number','avatar']
        });
        // 企业自己查看详情是不显示更多岗位的
        console.log(String(user_id),job.user_id)
        if(String(user_id)!==String(job.user_id)){
            const more_jobs = await ctx.model.JobOpening.findAll({
                where: {
                    user_id:job.user_id,
                    status:1,
                    del_flag:0,
                    id:{
                        [ctx.model.Sequelize.Op.notIn]:[job.id]
                    }
                },
                include: [
                    { model: ctx.model.Position, as: 'position',attributes: ['name', 'id'] },
                    { model: ctx.model.DictionaryDetail, as: 'workExperience',attributes: ['dict_value', 'dict_key','id'] },
                ],
                order: [['created_at', 'DESC']],
                limit
            });
            for (let itemJob of more_jobs) {
                itemJob = itemJob.dataValues;
                cuisine_ids = itemJob.cuisine_ids ? itemJob.cuisine_ids.split(',') : [];
                const employer = await ctx.model.EmployerInfo.findOne({
                    where: {
                        user_id:itemJob.user_id
                    },
                    attributes:['legal_representative','name','phone_number','avatar']
                });
                const cuisines = await ctx.model.DictionaryDetail.findAll({
                    where: {
                        dict_key: {
                            [ctx.model.Sequelize.Op.in]: cuisine_ids
                        }
                    } ,
                    attributes:['dict_value','dict_key','id']
                });
                itemJob.employer = employer
                itemJob.cuisines = cuisines
            }
            job.more_jobs = more_jobs
        }
        job.cuisines = cuisines;
        job.employer = employer;

        // 处理字典项名称
        const formatJob = {
            ...job,
            employer_info: job.employer ? {
                company_name: job.employer.company_name,
                business_license: job.employer.business_license
            } : null,
            work_experience_name: job.workExperience ? job.workExperience.name : ''
        };

        this.success(formatJob);
    }
    async userJobDetail() {
        const { ctx } = this;
        const { id } = ctx.params;
        const {user_id} = ctx.request.headers
        let job = await ctx.model.JobOpening.findByPk(id, {
            include: [
                { model: ctx.model.Position, as: 'position',attributes: ['name', 'id'] },
                { model: ctx.model.DictionaryDetail, as: 'workExperience',attributes: ['dict_value', 'dict_key','id'] },
            ]
        });
        if (!job) {
            ctx.throw(500, '职位不存在');
        }
        job = job.dataValues
        let cuisine_ids = job.cuisine_ids? job.cuisine_ids.split(',') : [];
        job.cuisines = await ctx.model.DictionaryDetail.findAll({
            where: {
                dict_key: {
                    [ctx.model.Sequelize.Op.in]: cuisine_ids
                }
            },
            attributes: ['dict_value', 'dict_key', 'id']
        })
        if(job.user_id!==user_id){
            const collect = await ctx.model.UserCollect.findOne({
                    where:{collect_id:id,user_id}
                }
            )
            job.is_collect = !!collect
        }

        job.user = await ctx.model.UserResumes.findOne({
            where: {
                user_id: job.user_id
            }
        })
        if(job.user){
            job.experience = await ctx.model.UserResumeExperience.findAll({
                where:{
                    resume_id:job.user.id
                },
                attributes:['company_name','position','work_start_time','work_end_time']
            })
        }
        this.success(job);
    }
    async employerUpdateStatus(){
        const { ctx } = this;
        const {id} = ctx.request.body;
        const job = await ctx.model.JobOpening.findByPk(id)
        if (!job) {
            ctx.throw(500,'该职位不存在')
        }
        await job.update({status:!job.status})
        this.success()
    }
    async myJobList(){
        const { ctx } = this;
        const {user_id} = ctx.request.headers
        const { status='', page = 1, pageSize = 10 } = ctx.query;

        const where = {
            del_flag: 0,
            user_id
        };
        if(status) where.status = status;
        const { count, rows } = await ctx.model.JobOpening.findAndCountAll({
            where,
            order: [['created_at', 'DESC']],
            offset: (page - 1) * pageSize,
            limit: parseInt(pageSize),
            attributes:['id','public_time','min_salary','max_salary','work_place','work_experience_id','position_id','status'],
            include: [
                { model: ctx.model.Position, as: 'position',attributes: ['name', 'id'] },
                { model: ctx.model.DictionaryDetail, as: 'workExperience',attributes: ['dict_value', 'dict_key','id'] },
            ]
        });

        this.success({
            list: rows,
            pagination: {
                total: count,
                current: parseInt(page),
                pageSize: parseInt(pageSize),
            }
        })
    }
    async employerCreate() {
        const { ctx } = this;
        const { user_id } = ctx.request.headers
        const rules = {
            position_id: { type: 'number', required: true, message: '请选择职位' },
            job_requirements: { type: 'string', required: true, message: '请输入岗位要求' },
            cuisine_ids: { type: 'string', required: false, message: '请选择菜系' },
            work_experience_id: { type: 'string', required: true, message: '请选择工作年限' },
            min_salary: { type: 'string', required: true, message: '请输入最低薪资' },
            max_salary: { type: 'string', required: true, message: '请输入最高薪资' },
        };
        if(ctx.request.body.user_type==='user') {
            delete rules.description
            delete rules.job_requirements
        }
        try {
            ctx.validate(rules);
        } catch (err) {
            ctx.throw(400, '字段校验失败');
        }

        const data = {
            ...ctx.request.body,
            user_id,
            public_time: new Date()
        };
        const job = await ctx.model.JobOpening.create(data);
        this.success(job);
    }

    async employerUpdate() {
        const { ctx } = this;
        const body = ctx.request.body
        const rules = {
            position_id: { type: 'number', required: true, message: '请选择职位' },
            job_requirements: { type: 'string', required: true, message: '请输入岗位要求' },
            cuisine_ids: { type: 'string', required: false, message: '请选择菜系' },
            work_experience_id: { type: 'string', required: true, message: '请选择工作年限' },
            min_salary: { type: 'string', required: true, message: '请输入最低薪资' },
            max_salary: { type: 'string', required: true, message: '请输入最高薪资' },
        };
        if(ctx.request.body.user_type==='user') {
            delete rules.description
            delete rules.job_requirements
        }
        try {
            ctx.validate(rules);
        } catch (err) {
            ctx.throw(400, '字段校验失败');
        }
        if(!body.id){
            ctx.throw(500,'参数错误')
        }
        const job = await ctx.model.JobOpening.findByPk(body.id);
        if(!job){
            ctx.throw(500,'职位不存在')
        }
        await job.update(body)
        this.success();
    }
}

module.exports = JobOpeningController;
